<!-- 商品列表-新增商品 -->
<template>
  <div class="app-container">
    <div class="new-goods">新增商品</div>
    <el-form
      :model="commodityForm"
      :rules="commodityFormRule"
      ref="commodityFormRef"
      size="medium"
      style="margin: 0px 50px"
    >
      <el-row :gutter="120">
        <el-col :span="12">
          <!-- <el-form-item
            label="油企名称"
            prop="enterpriseId"
            :label-width="formLabelWidth"
            v-if="['', null].includes($store.state.user.userLevel)"
          >
            <el-select
              v-model="commodityForm.enterpriseId"
              placeholder="请选择油企名称"
              style="width: 100%"
              :clearable="true"
              filterable
              @change="handleSelectChange"
              :disabled="action === 'detail'"
            >
              <el-option
                v-for="(item, index) in enterpriseList"
                :key="index"
                :value="item.enterpriseId"
                :label="item.enterpriseName"
              ></el-option>
            </el-select>
          </el-form-item>-->
          <el-form-item
            label="油站名称"
            prop="stationId"
            :label-width="formLabelWidth"
            v-if="!['2'].includes($store.state.user.userLevel)&& !['', null].includes($store.state.user.userLevel)"
          >
            <el-select
              v-model="commodityForm.stationId"
              placeholder="请选择油站名称"
              style="width: 100%"
              :clearable="true"
              filterable
              :disabled="action === 'detail'"
            >
              <el-option label="所有油站" value="all"></el-option>
              <el-option
                v-for="item in stationList"
                :key="item.stationId"
                :label="item.stationName"
                :value="item.stationId"
              >
              </el-option>
            </el-select>
          </el-form-item> 
          <el-form-item
            label="仓库名称"
            prop="stationId"
            clearable
            size="small"
            :label-width="formLabelWidth"
            v-if="['', null].includes($store.state.user.userLevel)"
          >
            <el-select
              v-model="commodityForm.stationId"
              :clearable="true"
              filterable
              style="width: 100%"
              placeholder="请选择仓库名称"
            >
              <el-option v-for="item in stationList" :key="item.stationId" :value="item.stationId" :label="item.stationName"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="商品名称"
            prop="commodityName"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="commodityForm.commodityName"
              placeholder="请输入商品名称"
              :disabled="action === 'detail'"
            ></el-input>
          </el-form-item>

          <el-form-item label="商品编码" :label-width="formLabelWidth">
            <el-input
              v-model="commodityForm.commodityCode"
              disabled
              placeholder="商品编号，系统自动生成"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="商品条形码"
            :label-width="formLabelWidth"
            prop="barCode"
          >
            <el-input
              v-model="commodityForm.barCode"
              :disabled="action === 'detail'"
              placeholder="请输入商品条形码"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="所属分类"
            :label-width="formLabelWidth"
            prop="categoryId"
          >
            <treeselect
              v-model="commodityForm.categoryId"
              :options="categoryOptions"
              :normalizer="normalizer"
              :show-count="true"
              placeholder="请选择"
              :disabled="action === 'detail'"
            />
          </el-form-item>

          <el-form-item
            label="供应商"
            prop="supplierId"
            :label-width="formLabelWidth"
          >
            <el-select
              v-model="commodityForm.supplierId"
              placeholder="请选择供应商"
              style="width: 100%"
              :disabled="action === 'detail'"
            >
              <el-option
                v-for="item in supplierList"
                :key="item.supplierId"
                :label="item.supplierName"
                :value="item.supplierId"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            label="进货价格"
            :label-width="formLabelWidth"
            prop="retailPrice"
          >
            <el-input
              v-model="commodityForm.retailPrice"
              placeholder="请输入进货价格"
              :disabled="action === 'detail'"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item
            label="销售价格"
            :label-width="formLabelWidth"
            prop="salePrice"
          >
            <el-input
              v-model="commodityForm.salePrice"
              placeholder="请输入进货价格"
              :disabled="action === 'detail'"
            ></el-input>
          </el-form-item>
          <el-form-item label="单位" :label-width="formLabelWidth" prop="unit">
            <el-input
              v-model="commodityForm.unit"
              placeholder="请输入单位"
              :disabled="action === 'detail'"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="税率(%)"
            :label-width="formLabelWidth"
            prop="taxRate"
          >
            <el-input-number
              v-model="commodityForm.taxRate"
              :min="0"
              :max="100"
              :precision="2"
              :step="0.1"
              placeholder="请输入税率(%)"
              style="width: 100%"
              :disabled="action === 'detail'"
            ></el-input-number>
          </el-form-item>

          <el-form-item
            label="图片"
            :label-width="formLabelWidth"
            style="position: relative"
          >
            <el-upload
              class="avatar-uploader"
              :action="imgUpConfig.addressUrl"
              :headers="imgUpConfig.headers"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              <div class="el-upload__tip" slot="tip">
                只能上传jpg/png文件,且不超过5M
              </div>
            </el-upload>
            <div class="deleimg-icon" v-if="imageUrl">
              <i class="el-icon-delete" @click="handleRemove"></i>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="goods-button">
      <el-button
        round
        size="medium"
        style="margin-right: 60px"
        @click="handleCancel"
        >取消</el-button
      >
      <el-button type="primary" round size="medium" @click="handleSubmit"
        >确定</el-button
      >
    </div>
  </div>
</template>
<script>
import { cloneDeep } from "lodash";
import {
  enterpriseList,
  listEnterpriseStation,
} from "@/api/nonOil/putlntoStorage";
import {
  getRepositoryApi
} from "@/api/nonOil/class";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import { getNonOilCategoryTreeApi, supplierAllList } from "@/api/nonOil/class";
import { addCommodityInfoApi, editCommodityInfoApi } from "@/api/nonOil/goods";
export default {
  name: "ProductsListAdd",
  components: { Treeselect },
  data() {
    // 分类id
    let checkCategory = (rule, value, callback) => {
      if (!this.commodityForm.categoryId) callback(new Error("请选择分类"));
      callback();
    };
    // 销售价格
    let checkSalePrice = (rule, value, callback) => {
      let amount = Number(String(value).trim());
      const reg = /^\d+(\.\d{1,2})?$/;
      if (value === "") return callback(new Error("请输入价格"));
      if (amount < 0) return callback(new Error("价格不能小于0"));
      if (Number.isNaN(amount)) return callback(new Error("请输入合法数字"));
      if (!reg.test(amount)) return callback(new Error("价格最多保留两位小数"));
      callback();
    };

    return {
      action: null,
      imageUrl: null,

      stationList: [],
      enterpriseList: [],
      supplierList: [],
      categoryOptions: [],

      imgUpConfig: {
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        addressUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      },

      formLabelWidth: "100px",

      commodityForm: {
        enterpriseId: null,
        stationId: null,
        commodityName: null,
        categoryId: null,
        commodityCode: null,
        barCode: null,
        supplierId: null,
        retailPrice: null,
        salePrice: null,
        unit: null,
        taxRate: null,
        image: null,
      },

      commodityFormRule: {
        enterpriseId: [
          { required: true, message: "请选择油企名称", trigger: "change" },
        ],
        stationId: [
          { required: true, message: "请选择油站名称", trigger: "change" },
        ],
        commodityName: [
          { required: true, message: "请输入商品名称", trgger: "change" },
        ],
        barCode: [
          { required: true, message: "请输入商品条形码", trigger: "change" },
        ],
        categoryId: [
          { required: true, validator: checkCategory, trgger: "change" },
        ],
        supplierId: [
          { required: true, message: "请选择供应商", trigger: "change" },
        ],
        retailPrice: [
          { required: false, validator: checkSalePrice, trgger: "change" },
        ],
        salePrice: [
          { required: true, validator: checkSalePrice, trgger: "change" },
        ],
        unit: [
          { required: true, message: "请输入单位", trigger: "change" },
          {
            min: 1,
            max: 15,
            message: "单位长度在 1 到 15 个字符",
            trigger: "change",
          },
        ],
      },
    };
  },
  created() {
    if (!this.$route.query.action && !this.$route.query.commodityForm)
      return this.handleCancel();
    // 油企
    if (this.presentEnterprise && this.presentEnterprise.enterpriseId) {
      this.commodityForm.enterpriseId = this.presentEnterprise.enterpriseId;
      this.getStationList(this.commodityForm.enterpriseId);
    }
    // 油站账号登录
    if (this.presentSation) {
      this.commodityForm.stationId = this.presentSation;
    }
    this.getEnterpriseList();
    this.getNonOilCategoryTree();
    this.supplierAllList();
    this.getRepositoryList()
    this.action = this.$route.query.action;
    this.commodityForm = JSON.parse(this.$route.query.commodityForm);
    // 图片回显
    this.imageUrl = this.commodityForm.image;

    this.supplierList = [
      {
        supplierId: this.commodityForm.supplierId,
        supplierName: this.commodityForm.supplierName,
      },
    ];
  },
  methods: {
    async getRepositoryList(){
      const res=await getRepositoryApi()
      if(res){ 
        this.stationList=res
      }
    },
    // 提交
    handleSubmit() {
      if (this.action === "detail") return this.handleCancel();
      this.$refs.commodityFormRef.validate((valid) => {
        if (valid) {
          const params = cloneDeep(this.commodityForm);

          if (params.stationId == "all") {
            params.isAll = "all";
            params.stationId = null;
          }
          if (this.presentSation) {
            params.stationId = this.presentSation;
          }
          if (this.commodityForm.commodityId) {
            // 编辑
            editCommodityInfoApi(params).then((res) => {
              this.msgSuccess("编辑商品成功");
              this.handleCancel();
            });
          } else {
            //   // 新增
            addCommodityInfoApi(params).then((res) => {
              this.msgSuccess("添加商品成功");
              this.handleCancel();
            });
          }
        } else {
          console.log("error submit");
        }
      });
    },

    // 取消
    handleCancel() {
      this.$router.push({
        path: "/nonOil/productsList",
      });
    },

    // 获取供应商
    supplierAllList() {
      supplierAllList()
        .then((res) => {
          this.supplierList = res.data;
        })
        .catch(() => {
          this.supplierList = [];
        });
    },

    // 获取分类树
    async getNonOilCategoryTree() {
      const res = await getNonOilCategoryTreeApi();
      this.categoryOptions = this.handleTree(res.data.children, "categoryId");
      // 编辑分类下拉项
    },

    /** 转换分类数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.categoryId,
        label: node.categoryName,
        children: node.children,
      };
    },

    // 查询油企
    getEnterpriseList() {
      enterpriseList().then((res) => {
        this.enterpriseList = res.rows;
      });
    },

    // 请选择油企
    handleSelectChange(value) {
      this.stationList = [];
      this.commodityForm.stationId = null;
      this.getStationList(value);
    },

    // 查询油站
    getStationList(val) {
      listEnterpriseStation({ enterpriseId: val, status: "1" }).then((res) => {
        this.stationList = res;
      });
    },

    // 图片上传前的校验
    beforeAvatarUpload(file) {
      const imgtypes = ["image/jpeg", "image/png"];
      if (!imgtypes.includes(file.type)) {
        this.msgError("图片只能是jpg或png格式");
        return false;
      }
      let isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.msgError("图片大小不能超过5m");
        return false;
      }
    },

    // 图片上传成功
    handleAvatarSuccess(response, file, fileList) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.commodityForm.image = response.url;
    },

    // 删除图片
    handleRemove(file) {
      if (this.action !== "detail") {
        this.imageUrl = "";
        this.commodityForm.image = "";
      }
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-input-number {
  .el-input-number__decrease {
    display: none;
  }

  .el-input-number__increase {
    display: none;
  }

  div .el-input__inner {
    text-align: left;
    padding: 0px 0px 0px 15px;
  }
}

// 分类
::v-deep .vue-treeselect__control {
  height: 36px;
}

.goods-button {
  width: 100%;
  text-align: center;
  margin-top: 80px;
}

.new-goods {
  width: 100%;
  height: 45px;
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 45px;
  border-bottom: 1px solid #000;
}

/* 图片样式 */

.deleimg-icon {
  width: 178px;
  height: 178px;
  position: absolute;
  left: 0;
  top: 0;
  font-size: 20px;
  color: #fff;
  background: rgba(0, 0, 0, 0.4);

  i {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%);
  }

  :hover {
    cursor: pointer;
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  border: 1px dashed #d9d9d9;
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
